package com.wyman.context.annotation;

import cn.hutool.core.util.StrUtil;
import com.wyman.beans.factory.config.BeanDefinition;
import com.wyman.beans.factory.support.BeanDefinitionRegistry;
import com.wyman.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * @Author 李伟民
 * @Description
 * @DateTime 2024/12/29 23:01
 */
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider{

    private BeanDefinitionRegistry registry;

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry){
        this.registry = registry;
    }

    public void doScan(String... basePackages){
        for(String basePackage:basePackages){
            Set<BeanDefinition> beanDefinitionSet = findCandidateComponents(basePackage);
            for(BeanDefinition beanDefinition:beanDefinitionSet){

                String scope = resolveBeanScope(beanDefinition);
                if(StrUtil.isNotEmpty(scope)){
                    beanDefinition.setScope(scope);
                }
                registry.registerBeanDefinition(determineBeanName(beanDefinition),beanDefinition);
            }
        }
    }



    //解析component注解 获取beanName

    private String determineBeanName(BeanDefinition beanDefinition){
        Class<?> beanClass = beanDefinition.getBeanClass();
        Component component = beanClass.getAnnotation(Component.class);
        if(component!=null){
            return component.value();
        }
        else {
            return StrUtil.lowerFirst(beanClass.getSimpleName());
        }

    }

    //解析Scope注解 获取作用域
    private String resolveBeanScope(BeanDefinition beanDefinition){
        Class<?> beanClass = beanDefinition.getBeanClass();
        Scope scope = beanClass.getAnnotation(Scope.class);
        if(scope!=null){
            return scope.value();
        }
        return StrUtil.EMPTY;
    }
}
